package com.expertria.glex.view;

import com.expertria.glex.view.layout.ILayout;
 
import com.expertria.glex.view.layout.VerticalLayout;
import com.expertria.glex.view.renderer.IRenderer;
 
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.uibinder.client.UiConstructor;
 

public class Repeater extends Group implements IRepeater {


	protected IRenderer renderer;
	protected  Object data;
	
	
	/**
	 * Default Layout to be Vertical
	 */
	public Repeater()
	
	{
		this(new VerticalLayout());
	}
	
	public Repeater(ILayout layout) {
	
		super(layout);
	}
	
	public   @UiConstructor Repeater(ILayout layout, Object data, IRenderer renderer)
	{
		super(layout);
		
		this.setRender(renderer);
		this.setData(data);
	}
	/*
	 * Set the data to render out the repeater
	 * The data should be the instanceof JsArray or Iterable
	 */
	@SuppressWarnings("unchecked")
	public void  setData(Object data)   
	{
		 
		this.data = data;
		this.basePanel. clear();
		if(this.renderer != null)
		{
			//do something
			if(data instanceof JsArray)
			{
				JsArray<JavaScriptObject> array = (JsArray<JavaScriptObject>) data;
				for(int i = 0 ; i < array.length() ; i++)
				{
					createObject(array.get(i));
					
				}
			}
			else if(data instanceof Iterable)
			{
				for(Object o : (Iterable)data)
				{
					createObject(o);
					 
				}
			}
			else if(data instanceof Object [])
			{
				Object [] o = (Object []) data;
				for(int i = 0 ; i < o.length  ;i++)
				{
					createObject(o[i]);
				}
			}
		}
		
		
		 
	}
	
	private void createObject(Object o) 
	{
		try
		{
			//we have to do this due to ISSUE 2243
			//please vote for ISSUE 2243 to be fix in next version of GWT
			IRenderer item = renderer.instance();
			item.render(o);
			this.addWidget(item.getWidget());
		 
		}
		//throws IllegalAccessException, InstantiationException
		catch(Exception e)
		{
			
		}
		 
		finally
		{
			//do nothing
		}
	}
	
	/**
	 * Limited due to ISSUE 2243
	 * {@link http://code.google.com/p/google-web-toolkit/issues/detail?id=2243} 
	 * @param renderer
	 */
	public void setRender(IRenderer  renderer)
	{
		this.renderer = renderer;
		 
	}
	
	public void invalidate()
	{
		//invalidate the container
		this.layout.updateDisplayList();
		
		//can should override this method to invalidate any child 
	}
	
}
